package com.xiaoxu.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.xiaoxu.auth.model.dto.AuthParamsDto;
import com.xiaoxu.auth.model.dto.UserExt;
import com.xiaoxu.auth.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author xiaoxu
 * @version 1.0
 * @description TODO
 * @date 2023/2/2 13:05
 */
@Service
@Slf4j
public class BaseUserService implements UserDetailsService {

    private final ApplicationContext applicationContext;

    public BaseUserService(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public UserDetails loadUserByUsername(String params) throws UsernameNotFoundException {
        AuthParamsDto authParamsDto;
        try {
             authParamsDto = JSON.parseObject(params, AuthParamsDto.class);
        }catch (Exception e){
            log.info("认证请求不正确: \n 请求: {},错误: {}",params,e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("认证请求数据格式不正确");
        }
        String authType = authParamsDto.getAuthType();
        AuthService authService = applicationContext.getBean(authType + "_authservice",AuthService.class);
        //开始认证
        UserExt userExt = authService.execute(authParamsDto);

        return getUserPrincipal(userExt);
    }

    private UserDetails getUserPrincipal(UserExt userExt){
        //用户权限,如果不加报Cannot pass a null GrantedAuthority collection
        String[] authorities = userExt.getPermissions().toArray(new String[0]);
        String password = userExt.getPassword();
        //为了安全在令牌中不放密码
        userExt.setPassword(null);
        //将user对象转json
        String userString = JSON.toJSONString(userExt);
        //创建UserDetails对象
        return org.springframework.security.core.userdetails.User.withUsername(userString).password(password).authorities(authorities).build();

    }
}
